<template>
  <div class="labor-type-management">
    <el-card>
      <div slot="header" class="card-header">
        <span class="card-title">劳务类型管理</span>
        <el-button type="primary" @click="handleAdd" class="add-button">
          <i class="el-icon-plus"></i>
          添加类型
        </el-button>
      </div>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <el-row :gutter="20" class="search-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索类型名称或描述"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch"
              clearable
            />
          </el-col>
          <el-col :xs="12" :sm="6" :md="4" :lg="4" :xl="4">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 100%">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-col>
          <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
            <div class="search-buttons">
              <el-button type="primary" @click="handleSearch" size="small">搜索</el-button>
              <el-button @click="handleReset" size="small">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 劳务类型列表 -->
      <el-table
        :data="typeList"
        v-loading="loading"
        stripe
        border
        size="medium"
        style="width: 100%"
        :default-sort="{prop: 'sortOrder', order: 'ascending'}"
        :fit="true"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="typeName" label="类型名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="icon" label="图标" width="80" align="center">
          <template slot-scope="scope">
            <i :class="scope.row.icon" v-if="scope.row.icon" style="font-size: 18px; color: #409eff;"></i>
            <span v-else style="color: #c0c4cc; font-size: 12px;">无</span>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80" align="center" sortable />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template slot-scope="scope">
            <div class="action-buttons">
              <el-button size="mini" @click="handleView(scope.row)" icon="el-icon-view">查看</el-button>
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)" icon="el-icon-edit">编辑</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)" trigger="click">
                <el-button size="mini">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="scope.row.status === 1 ? 'disable' : 'enable'">
                    <i :class="scope.row.status === 1 ? 'el-icon-lock' : 'el-icon-unlock'"></i>
                    {{ scope.row.status === 1 ? '禁用' : '启用' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    <i class="el-icon-delete"></i>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </el-card>

    <!-- 劳务类型详情/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        :model="typeForm"
        :rules="typeRules"
        ref="typeForm"
        label-width="100px"
      >
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="typeForm.typeName" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="typeForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入类型描述"
          />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="typeForm.icon" placeholder="请输入图标类名，如：el-icon-briefcase">
            <template slot="append">
              <el-button @click="showIconSelector">选择图标</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number 
            v-model="typeForm.sortOrder" 
            :min="0" 
            :max="999"
            placeholder="请输入排序值"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="typeForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 劳务类型详情对话框 -->
    <el-dialog
      title="劳务类型详情"
      :visible.sync="detailDialogVisible"
      width="500px"
    >
      <div v-if="currentType" class="type-detail">
        <div class="detail-item">
          <label>ID:</label>
          <p>{{ currentType.id }}</p>
        </div>
        <div class="detail-item">
          <label>类型名称:</label>
          <p>{{ currentType.typeName }}</p>
        </div>
        <div class="detail-item">
          <label>描述:</label>
          <p>{{ currentType.description }}</p>
        </div>
        <div class="detail-item">
          <label>图标:</label>
          <p>
            <i :class="currentType.icon" v-if="currentType.icon" style="font-size: 20px;"></i>
            <span v-else>无图标</span>
          </p>
        </div>
        <div class="detail-item">
          <label>排序:</label>
          <p>{{ currentType.sortOrder }}</p>
        </div>
        <div class="detail-item">
          <label>状态:</label>
          <p>
            <el-tag :type="currentType.status === 1 ? 'success' : 'danger'" size="small">
              {{ currentType.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </p>
        </div>
        <div class="detail-item">
          <label>创建时间:</label>
          <p>{{ formatDate(currentType.createdAt) }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 图标选择器对话框 -->
    <el-dialog
      title="选择图标"
      :visible.sync="iconSelectorVisible"
      width="600px"
    >
      <div class="icon-selector">
        <div class="icon-grid">
          <div 
            v-for="icon in iconList" 
            :key="icon"
            class="icon-item"
            :class="{ active: typeForm.icon === icon }"
            @click="selectIcon(icon)"
          >
            <i :class="icon"></i>
            <span>{{ icon }}</span>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="iconSelectorVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmIcon">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "LaborTypeManagement",
  data() {
    return {
      loading: false,
      submitLoading: false,
      typeList: [],
      searchForm: {
        keyword: "",
        status: ""
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      dialogVisible: false,
      detailDialogVisible: false,
      iconSelectorVisible: false,
      dialogTitle: "",
      isEdit: false,
      currentType: null,
      selectedIcon: "",
      typeForm: {
        id: null,
        typeName: "",
        description: "",
        icon: "",
        sortOrder: 0,
        status: 1
      },
      typeRules: {
        typeName: [
          { required: true, message: "请输入类型名称", trigger: "blur" }
        ],
        description: [
          { required: true, message: "请输入类型描述", trigger: "blur" }
        ],
        sortOrder: [
          { required: true, message: "请输入排序值", trigger: "blur" }
        ]
      },
      iconList: [
        "el-icon-briefcase",
        "el-icon-shopping-cart-2",
        "el-icon-reading",
        "el-icon-truck",
        "el-icon-tickets",
        "el-icon-star-on",
        "el-icon-trophy",
        "el-icon-medal",
        "el-icon-present",
        "el-icon-gift",
        "el-icon-coffee",
        "el-icon-food",
        "el-icon-house",
        "el-icon-office-building",
        "el-icon-school",
        "el-icon-location",
        "el-icon-map-location",
        "el-icon-phone",
        "el-icon-message",
        "el-icon-chat-dot-round"
      ]
    }
  },
  async created() {
    await this.loadTypeList()
  },
  methods: {
    async loadTypeList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
        const response = await this.$http.get("/admin/labor-types", { params })
        console.log("劳务类型API响应:", response.data)
        if (response.data.code === 200) {
          // 处理不同的数据结构
          const data = response.data.data
          if (Array.isArray(data)) {
            this.typeList = data
            this.pagination.total = data.length
          } else if (data && data.list) {
            this.typeList = data.list
            this.pagination.total = data.total || data.list.length
          } else if (data && Array.isArray(data.records)) {
            this.typeList = data.records
            this.pagination.total = data.total || data.records.length
          } else {
            this.typeList = data || []
            this.pagination.total = Array.isArray(data) ? data.length : 0
          }
          console.log("劳务类型数据:", this.typeList)
          console.log("分页总数:", this.pagination.total)
        } else {
          console.error("API返回错误:", response.data.message)
          this.typeList = []
          this.pagination.total = 0
        }
      } catch (error) {
        console.error("加载劳务类型列表失败:", error)
        // 使用模拟数据
        this.loadMockData()
      } finally {
        this.loading = false
      }
    },

    loadMockData() {
      this.typeList = [
        {
          id: 1,
          typeName: "兼职工作",
          description: "各种兼职工作机会，包括服务员、促销员、家教等",
          icon: "el-icon-briefcase",
          sortOrder: 1,
          status: 1,
          createdAt: "2025-09-20T10:00:00"
        },
        {
          id: 2,
          typeName: "跑腿服务",
          description: "代取快递、代买物品、代排队等跑腿服务",
          icon: "el-icon-shopping-cart-2",
          sortOrder: 2,
          status: 1,
          createdAt: "2025-09-19T14:30:00"
        },
        {
          id: 3,
          typeName: "代课服务",
          description: "代上课程、代写作业、代考试等学习相关服务",
          icon: "el-icon-reading",
          sortOrder: 3,
          status: 1,
          createdAt: "2025-09-18T09:15:00"
        },
        {
          id: 4,
          typeName: "快递代取",
          description: "代取快递包裹并送到指定地点",
          icon: "el-icon-truck",
          sortOrder: 4,
          status: 1,
          createdAt: "2025-09-17T16:20:00"
        }
      ]
      this.pagination.total = 4
    },

    handleSearch() {
      this.pagination.currentPage = 1
      this.loadTypeList()
    },

    handleReset() {
      this.searchForm = {
        keyword: "",
        status: ""
      }
      this.pagination.currentPage = 1
      this.loadTypeList()
    },

    handleAdd() {
      this.dialogTitle = "添加劳务类型"
      this.isEdit = false
      this.typeForm = {
        id: null,
        typeName: "",
        description: "",
        icon: "",
        sortOrder: 0,
        status: 1
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = "编辑劳务类型"
      this.isEdit = true
      this.typeForm = {
        id: row.id,
        typeName: row.typeName,
        description: row.description,
        icon: row.icon,
        sortOrder: row.sortOrder,
        status: row.status
      }
      this.dialogVisible = true
    },

    handleView(row) {
      this.currentType = row
      this.detailDialogVisible = true
    },

    async handleToggleStatus(row) {
      const newStatus = row.status === 1 ? 0 : 1
      const action = newStatus === 1 ? '启用' : '禁用'
      
      try {
        await this.$confirm(`确定要${action}该劳务类型吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.$http.put(`/admin/labor-types/${row.id}/status`, {
          status: newStatus
        })
        
        if (response.data.code === 200) {
          this.$message.success(`${action}成功`)
          this.loadTypeList()
        } else {
          this.$message.error(response.data.message || `${action}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error(`${action}劳务类型失败:`, error)
          this.$message.error(`${action}失败`)
        }
      }
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该劳务类型吗？删除后不可恢复！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.$http.delete(`/admin/labor-types/${row.id}`)
        
        if (response.data.code === 200) {
          this.$message.success('删除成功')
          this.loadTypeList()
        } else {
          this.$message.error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除劳务类型失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    async handleSubmit() {
      try {
        await this.$refs.typeForm.validate()
        this.submitLoading = true

        const url = this.isEdit ? `/admin/labor-types/${this.typeForm.id}` : '/admin/labor-types'
        const method = this.isEdit ? 'put' : 'post'
        
        const response = await this.$http[method](url, this.typeForm)
        
        if (response.data.code === 200) {
          this.$message.success(this.isEdit ? '更新成功' : '添加成功')
          this.dialogVisible = false
          this.loadTypeList()
        } else {
          this.$message.error(response.data.message || '操作失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('操作失败')
      } finally {
        this.submitLoading = false
      }
    },

    handleDialogClose() {
      this.$refs.typeForm.resetFields()
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.loadTypeList()
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadTypeList()
    },

    showIconSelector() {
      this.selectedIcon = this.typeForm.icon
      this.iconSelectorVisible = true
    },

    selectIcon(icon) {
      this.selectedIcon = icon
    },

    confirmIcon() {
      this.typeForm.icon = this.selectedIcon
      this.iconSelectorVisible = false
    },

    handleCommand(command, row) {
      switch (command) {
        case 'enable':
        case 'disable':
          this.handleToggleStatus(row)
          break
        case 'delete':
          this.handleDelete(row)
          break
      }
    },

    formatDate(date) {
      if (!date) return '未知'
      return new Date(date).toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.labor-type-management {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

/* 搜索区域样式 */
.search-area {
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
  padding: 16px;
  margin-bottom: 16px;
}

.search-row {
  display: flex;
  align-items: center;
}

.search-buttons {
  display: flex;
  gap: 8px;
}

/* 表格样式 */
.labor-type-management ::v-deep .el-table {
  border: 1px solid #e4e7ed;
}

.labor-type-management ::v-deep .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

/* 分页样式 */
.pagination-area {
  margin-top: 16px;
  text-align: right;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  margin: 0;
  padding: 6px 12px;
  font-size: 12px;
}

/* 详情对话框样式 */
.type-detail {
  padding: 16px 0;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
}

.detail-item label {
  font-weight: 500;
  color: #606266;
  margin-right: 12px;
  width: 80px;
  flex-shrink: 0;
}

.detail-item p {
  margin: 0;
  line-height: 1.5;
  flex: 1;
}

/* 图标选择器样式 */
.icon-selector {
  max-height: 400px;
  overflow-y: auto;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
  padding: 8px;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 8px;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  transition: border-color 0.2s;
}

.icon-item:hover {
  border-color: #409eff;
}

.icon-item.active {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.icon-item i {
  font-size: 20px;
  margin-bottom: 6px;
  color: #409eff;
}

.icon-item span {
  font-size: 11px;
  text-align: center;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .labor-type-management {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .search-area {
    padding: 12px;
  }
  
  .search-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .search-buttons {
    justify-content: center;
    width: 100%;
  }
  
  .pagination-area {
    text-align: center;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style>
